﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.Remoting.Messaging;

namespace CodeRepositoryConsole.Concurrency
{
    // the common language runtime automatically defines BeginInvoke 
    // and EndInvoke methods for this delegate, with the appropriate signatures. 
    // After calling BeginInvoke you can do the following: 
    // 1. Do some work and then call EndInvoke to block until the call completes.
    // 2. Obtain a WaitHandle using the IAsyncResult.AsyncWaitHandle property, 
    // use its WaitOne method to block execution until the WaitHandle is signaled, and then call EndInvoke.
    // 3. Poll the IAsyncResult returned by BeginInvoke to determine when 
    // the asynchronous call has completed, and then call EndInvoke. 
    // 4. Pass a delegate for a callback method to BeginInvoke.The method is executed 
    // on a ThreadPool thread when the asynchronous call completes. The callback method calls EndInvoke.

    // Important! No matter which technique you use, always call EndInvoke to complete your asynchronous call. 

    // see: https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously


    // Each call to BeginInvoke triggers a new request onto the .net thread pool.
    // It is perfectly acceptable to call BeginInvoke multiple times. Each IAsyncResult object is unique
    // to that specific call to BeginInvoke.
    // Note that delegates are immutable - calling BeginInvoke isn't going to change its state. You can safely
    // take a copy of a delegate reference, safe in the knowledge that calling Delegate.Combine etc will always
    // create a new delegate instance, rather than modifying the existing one.
    // see:https://stackoverflow.com/questions/2418107/why-can-you-call-begininvoke-more-than-once-on-the-same-delegate-instance

    public class AsyncDemo
    {
        // the method to be executed asynchronously.
        public string TestMethod(int callDuration,out int threadId)
        {
            Console.WriteLine("Test method begins");
            Thread.Sleep(callDuration);
            threadId = Thread.CurrentThread.ManagedThreadId;
            return String.Format("My call time was {0}.", callDuration.ToString());
        }
    }

    // The delegate must have the same signature as the method
    // it will call asynchronously.
    public delegate string AsyncMethodCaller(int callDuration, out int threadId);

    public class APMDelegate
    {
        /**
         * 1. Waiting for an Asynchronous Call with EndInvoke
         * The simplest way to execute a method asynchronously is to start executing the method by
         * calling the delegate's BeginInvoke method, do some work on the main thread, and then call 
         * the delegate's EndInvoke method.
         *
         * The parameters of EndInvoke include the out and ref parameters of the method that you want to 
         * execute asynchronously, plus the IAsyncResult returned by BeginInvoke.
         * Because EndInvoke might block, you should never call it from threads tht service the user interface.
         */
        public void EndByCallEndInvoke()
        {
            // The asynchronous method puts the thead id here.
            int threadId;

            // Create an instance of the test class.
            AsyncDemo ad = new AsyncDemo();

            // Create the delegate.
            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);

            // Initiate the asychronous call.
            IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null);

            Thread.Sleep(0);
            Console.WriteLine("Main thread {0} does some work.",
                Thread.CurrentThread.ManagedThreadId);

            string returnValue = caller.EndInvoke(out threadId, result);
            Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
                threadId, returnValue);

        }

        /**
         * 2. Waiting for an Asynchronous Call with WaitHandle
         * The WaitHandle is signaled when the asynchronous call completes, and you can wait for it by calling
         * the WaitOne method.          
         *
         * The wait handle is not closed automatically when you call EndInvoke. If you release all reference
         * to the wait handle, system resources are freed when garbage collection reclaims the wait handle.
         * To free the system resources as soon as you are finished using the wait handle, dispose of it by
         * calling the WaitHandle.Close method.
         */
        public void EndByCallWaitHandle()
        {
            // The asynchronous method puts the thread id here.
            int threadId;

            // Create an instance of the test class.
            AsyncDemo ad = new AsyncDemo();

            // Create the delegate
            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);

            IAsyncResult result = caller.BeginInvoke(3000,
                out threadId, null, null);

            Thread.Sleep(0);
            Console.WriteLine("Main thread {0} does some work.",
                Thread.CurrentThread.ManagedThreadId);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            // Perform additional processing here.
            // Call EndInvoke to retrieve the result.
            string returnValue = caller.EndInvoke(out threadId, result);

            // Close the wait handle
            result.AsyncWaitHandle.Close();

            Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
                Thread.CurrentThread.ManagedThreadId, returnValue);
        }

        /**
         * 3. Polling for Asynchronous Call Completion
         */
        public void EndByPolling()
        {
            // The asynchronous method puts the thead id here.
            int threadId;

            // Create an instance of the test class.
            AsyncDemo ad = new AsyncDemo();

            // Create the delegate.
            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);

            // Initiate the asychronous call.
            IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null);

            // Poll while simulating work
            while (result.IsCompleted == false)
            {
                Thread.Sleep(250);
                Console.WriteLine(".");
            }

            // Call EndInvoke to retrieve the results.
            string returnValue = caller.EndInvoke(out threadId, result);

            Console.WriteLine("\nThe call executed on thread {0}, with return value \"{1}\".", threadId, returnValue);
        }

        /**
         * 4. Executing a Callback Method When an Asynchronous Call Completion
         * In the callback method, you can cast the IAsyncResult, which is the only
         * parameter of the callback method, to an AsyncResult object. You can then
         * use the AsyncResult.AsyncDelegate property to get the delegate that was
         * used to initiate the call so that you can call EndInvoke.
         */
        public void EndByCallback()
        {
            // Create an instance of test class
            AsyncDemo ad = new AsyncDemo();

            // Create the delegate
            AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);

            // The threadId parameter of TestMethod is an out parameter, so
            // its input value is never used by TestMethod. Therefore, a dummy
            // variable can be passed to the BeginInvoke call. If the threadId
            // parameter were a ref parameter, it would have to be a class-
            // level field so that it could be passed to both BeginInvoke and 
            // EndInvoke.
            int dummy = 0;

            // Initiate the asynchronous call, passing three seconds (3000 ms)
            // for the callDuration parameter of TestMethod; a dummy variable 
            // for the out parameter (threadId); the callback delegate; and
            // state information that can be retrieved by the callback method.
            // In this case, the state information is a string that can be used
            // to format a console message.
            IAsyncResult result = caller.BeginInvoke(3000,
                out dummy,
                new AsyncCallback(CallbackMethod),
                "The call executed on thread {0}, with return value \"{1}\".");

            Console.WriteLine("The main thread {0} continues to execute...",
                Thread.CurrentThread.ManagedThreadId);

            // The callback is made on a ThreadPool thread. ThreadPool threads
            // are background threads, which do not keep the application running
            // if the main thread ends. Comment out the next line to demonstrate
            // this.
            Thread.Sleep(4000);

            Console.WriteLine("The main thread ends.");
        }

        static void CallbackMethod(IAsyncResult ar)
        {
            // Retrieve the delegate.
            AsyncResult result = (AsyncResult)ar;
            AsyncMethodCaller caller = (AsyncMethodCaller)result.AsyncDelegate;

            // Retrieve the format string that was passed as state information
            string formatString = (string)ar.AsyncState;

            // Define a variable to receive the value of the out parameter.
            // If the parameter were ref rather than out then it would have to
            // be a class-level field so it could also be passed to BeginInvoke.
            int threadId = 0;

            // Call EndInvoke to retrieve the results.
            string returnValue = caller.EndInvoke(out threadId, ar);

            // Use the format string to format the output message.
            Console.WriteLine(formatString,threadId,returnValue);
        }
    }
}
